package com.nirvana.flatbuffers;


import static com.nirvana.config.PluginConfig.tuplePattern;

/**
 * Copyright (c) 2022 Aoshu.Co.Ltd. All rights reserved.
 *
 * @author :    zhouqichun
 * @create :    2025/11/13 14:33
 * @description :
 **/
public class TupleResolver implements IResolve {
    @Override
    public boolean canResolve(String propertyType) {
        return tuplePattern.matcher(propertyType).matches();
    }

    @Override
    public String resolve(StringBuilder objectPreContent, String defName, String propertyName, String propertyType) {
        String[] types = propertyType.replaceAll("[()]", "").split(",");
        StringBuilder name = new StringBuilder();
        StringBuilder param = new StringBuilder();
        for (int i = 0; i < types.length; i++) {
            String type = types[i];
            String paramName = ", m.%s._%s".formatted(propertyName, i + 1);
            name.append(type.trim());
            param.append(paramName);
        }
        objectPreContent.append("""
                                            val %sOffset = Tuple%s.createTuple%s(builder%s)
                            """.formatted(propertyName, name, name, param));
        return "%sOffset".formatted(propertyName);
    }

    @Override
    public String resolveVector(StringBuilder objectPreContent, String defName, String propertyName, String propertyType) {
        String[] types = propertyType.replaceAll("[()]", "").split(",");
        StringBuilder name = new StringBuilder();
        StringBuilder param = new StringBuilder();
        for (int i = 0; i < types.length; i++) {
            String type = types[i];
            String paramName = ", p._%s".formatted(i + 1);
            name.append(type.trim());
            param.append(paramName);
        }
        objectPreContent.append("""
                                            val %sOffsets = m.%s.map(p => {
                                                Tuple%s.createTuple%s(builder%s)
                                            })
                            """.formatted(propertyName, propertyName, name, name, param));
        return "%sOffsets".formatted(propertyName);
    }
}
